package com.paas.form.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.jdbc.JdbcMeta;
import com.paas.common.jdbc.model.DbColumn;
import com.paas.common.jdbc.model.DbConfig;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.entity.FormAttributeEntity;
import com.paas.form.entity.FormAttributePubEntity;
import com.paas.form.entity.FormViewEntity;
import com.paas.form.entity.FormViewPubEntity;
import com.paas.form.service.IFormAttributePubService;
import com.paas.form.service.IFormAttributeService;
import com.paas.form.service.IFormViewPubService;
import com.paas.form.service.IFormViewService;
import com.paas.form.vo.HadAttrVo;
import com.publics.feign.service.IUcDataBaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/form/formAttribute")
@Api(description = "视图模块", tags = "")
public class FormAttributeController extends BaseController {

    @Autowired
    public IFormAttributeService formAttributeService;

    @Autowired
    public IFormAttributePubService formAttributePubService;

    @Autowired
    public IFormViewPubService formViewPubService;

    @Autowired
    public IBpmProcessInstanceService bpmProcessInstanceService;
    @Autowired
    public IUcDataBaseService dataBaseService;


    @Autowired
    public IFormViewService formViewService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormAttributeEntity formAttributeEntity) throws ParseException {
        if (BeanUtil.isNotEmpty(formAttributeEntity)) {
            injectUpdateDataAuth(formAttributeEntity);
            formAttributeEntity.setStatus(SystemConst.NORMAL_STATUS);
        }
        formAttributeService.save(formAttributeEntity);
    }

    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormAttributeEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
            for (FormAttributeEntity formAttributeEntity : list) {
                formAttributeEntity.setStatus(SystemConst.NORMAL_STATUS);
            }
        }
        formAttributeService.saveBatch(list);
    }

    @RequestMapping(value = "/attrHadCheck", method = RequestMethod.POST)
    @ApiOperation(value = "批量判断已存在属性", notes = "批量判断已存在属性")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量判断已存在属性")
    public List<String> attrHadCheck(@RequestBody HadAttrVo hadAttrVo) throws ParseException {
        List<String> codeList = hadAttrVo.getCodeList();
        String viewId = hadAttrVo.getViewId();
        if (codeList != null && codeList.size() > 0) {
            FormAttributeEntity attribute = new FormAttributeEntity();
            attribute.setViewId(viewId);
            List<FormAttributeEntity> formAttributeList = formAttributeService.getList(attribute);

            List<String> hadcodeList = new ArrayList<>();
            if (formAttributeList.size() > 0) {
                for (int i = 0; i < codeList.size(); i++) {
                    for (int j = 0; j < formAttributeList.size(); j++) {
                        if (formAttributeList.get(j).getCode().equals(codeList.get(i))) {
                            hadcodeList.add(codeList.get(i));
                        }
                    }
                }
                return hadcodeList;
            } else {
                return null;
            }
        }
        return null;
    }


    @RequestMapping(value = "/delectById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void delectById(String id) {
        if (null != id && !"".equals(id)) {
            FormAttributeEntity formAttributeEntity = new FormAttributeEntity();
            injectUpdateDataAuth(formAttributeEntity);
            formAttributeEntity.setId(id);
            formAttributeService.deleteByEntity(formAttributeEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormAttributeEntity formAttributeEntity = new FormAttributeEntity();
            injectUpdateDataAuth(formAttributeEntity);
            //formAttributeService.deleteBatchIds(ids);
            formAttributeService.deleteBatchIdsWithPermission(ids, formAttributeEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormAttributeEntity queryById(String id) {
        FormAttributeEntity bean = formAttributeService.getById(id);
        return bean;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List<FormAttributeEntity> queryBatchByIds(@RequestBody List<String> ids) {
        List<FormAttributeEntity> list = formAttributeService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage<FormAttributeEntity> queryPage(FormAttributeEntity formAttributeEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formAttributeEntity);
        IPage<FormAttributeEntity> pageBean = formAttributeService.getPage(formAttributeEntity, currentPage, pageSize);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List<FormAttributeEntity> queryList(FormAttributeEntity formAttributeEntity) {
        injectCheckDataAuth(formAttributeEntity);
        List<FormAttributeEntity> list = formAttributeService.getList(formAttributeEntity);
        return list;
    }

    @RequestMapping(value = "/finalAutogeneral", method = RequestMethod.GET)
    @ApiOperation(value = "生成定版", notes = "生成定版")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-生成定版")
    public RestResponse finalAutogeneral(String viewId, ProcessCmd processCmd, String newViewName) {
        BaseUserInfo baseUserInfo = getUserInfo();
        if (StringUtil.isNotEmpty(viewId)) {
            List<FormViewEntity> formViewEntityList = new ArrayList<>();
            // 根据id查询视图
            FormViewEntity formViewEntity = formViewService.getById(viewId);
            if (StringUtil.isNotEmpty(newViewName)) {
                formViewEntity.setName(newViewName);
            }

            List<FormViewPubEntity> viewPubEntityList = new ArrayList<>();
            List<FormAttributePubEntity> attributePubEntityList = new ArrayList<>();
            if (BeanUtil.isNotEmpty(formViewEntity)) {
                formViewEntityList.add(formViewEntity);
            }
            this.queryFormViewById(viewPubEntityList, attributePubEntityList, formViewEntityList);
            if (BeanUtil.isNotEmpty(processCmd)) {
                processCmd.setBusinessKey(formViewEntity.getId());
                processCmd.setData(JSON.toJSONString(formViewEntity));
                processCmd.setAppId(baseUserInfo.getAppId());
                bpmProcessInstanceService.startProcessInstance(processCmd);
            }
            if (viewPubEntityList.size() > 0) {
                formViewPubService.saveBatch(viewPubEntityList);
            }
            if (attributePubEntityList.size() > 0) {
                formAttributePubService.saveBatch(attributePubEntityList);
            }
        }
        return RestResponse.success();
    }

    @RequestMapping(value = "/queryListColumn")
    @ResponseBody
    @ApiOperation(value = "获取表对应的字段", notes = "获取表对应的字段")
    public List<DbColumn> queryListColumn(String databaseid, String tablename) {
        DataBaseEntity db = dataBaseService.queryJdbcById(databaseid);
        DbConfig dbConfig = new DbConfig(db.getJdbcDrivers(), db.getJdbcUrl(), db.getJdbcUser(),
                db.getJdbcPassword(), db.getDbName(), db.getDbType());
        JdbcMeta jdbc = new JdbcMeta(dbConfig);
        List<DbColumn> list = jdbc.getTableColumn(db.getDbName(), tablename);
        for (DbColumn dbColumn : list) {
            changeColumnType(dbColumn);
        }
        return list;
    }


    // 递归查询

    public void queryFormViewById(List<FormViewPubEntity> formViewPubList, List<FormAttributePubEntity> attributePubEntityList, List<FormViewEntity> list) {
        if (list.size() > 0) {
            for (FormViewEntity formViewEntity : list) {
                FormViewPubEntity formViewPub = BeanUtil.copyProperties(FormViewPubEntity.class, formViewEntity);
                formViewPubList.add(formViewPub);
                FormAttributeEntity formAttributeEntity = new FormAttributeEntity();
                formAttributeEntity.setViewId(formViewEntity.getId());
                List<FormAttributeEntity> formAttributeEntityList = formAttributeService.getList(formAttributeEntity);
                if (formAttributeEntityList != null && formAttributeEntityList.size() > 0) {
                    for (FormAttributeEntity formAttribute : formAttributeEntityList) {
                        FormAttributePubEntity formAttributePubEntity = BeanUtil.copyProperties(FormAttributePubEntity.class, formAttribute);
                        attributePubEntityList.add(formAttributePubEntity);
                    }
                }
                FormViewEntity formView = new FormViewEntity();
                formView.setViewId(formViewEntity.getId());
                List<FormViewEntity> formViewEntityList = formViewService.getList(formView);
                if (formViewEntityList != null && formViewEntityList.size() > 0) {
                    queryFormViewById(formViewPubList, attributePubEntityList, formViewEntityList);
                }
            }
        }
    }


    private void changeColumnType(DbColumn dbColumn) {
        switch (dbColumn.getDataType()) {
            case Types.TIME:
                dbColumn.setDataTypeName("date");
                break;
            case Types.TIMESTAMP:
                dbColumn.setDataTypeName("date");
                break;
            case Types.DATE:
                dbColumn.setDataTypeName("date");
                break;
            case Types.DECIMAL:
                dbColumn.setDataTypeName("number");
                break;
            case Types.DOUBLE:
                dbColumn.setDataTypeName("number");
                break;
            case Types.FLOAT:
                dbColumn.setDataTypeName("number");
                break;
            case Types.INTEGER:
                dbColumn.setDataTypeName("number");
                break;
            case Types.BIGINT:
                dbColumn.setDataTypeName("number");
                break;
            case Types.NUMERIC:
                dbColumn.setDataTypeName("number");
                break;
            default:
                dbColumn.setDataTypeName("string");
                break;
        }
    }

}